<script setup>
import Toast from '@vant/weapp/dist/toast/toast';
import newLoading from '@/components/newLoading/index.vue';
import imgCreateVideo from './child/imgCreateVideo.vue';
import textCreateVideo from './child/textCreateVideo.vue';
import { aiGenerationVideo, editImgUpload, getImageByTaskId } from '@/api/painting'
import { getCategoryDetail } from '@/api/home'

import { ref, computed } from 'vue';
import { onLoad, onUnload } from '@dcloudio/uni-app'


// 页面携带参数
const queryItem = ref({})
// 查询详情信息
const queryInfo = ref({})
// 页面参数
const queryParams = ref({})
// 页面提交参数
const queryData = ref({})


// tabs选中
const tabsCurrent = ref(0);

// 文生视频Ref
const textCreateVideoRef = ref(null);
// 图生视频Ref
const imgCreateVideoRef = ref(null);




const loading = ref(false);
const loadingRef = ref(null);

let timer = null;
const taskId = ref('')

// 消耗算力基准
const oldExpendNum = ref(0)
// 消耗算力
const expendNum = computed(() => {
    const videoType = queryParams.value.resolution + queryParams.value.duration
    let consumeImgNum = 0
    if ("480p5" == videoType) {
        consumeImgNum = oldExpendNum.value * 1;
    } else if ("480p10" == videoType) {
        consumeImgNum = oldExpendNum.value * 2;
    } else if ("720p5" == videoType) {
        consumeImgNum = oldExpendNum.value * 2;
    } else if ("720p10" == videoType) {
        consumeImgNum = oldExpendNum.value * 4;
    } else {
        consumeImgNum = oldExpendNum.value * 1;
    }
    return consumeImgNum
})



// 开设生成视频
async function startFn() {
    clearInterval(timer);
    if (tabsCurrent.value === 0) {
        queryData.value = {}
        await textCreateVideoRef.value.getQueryParams()
    } else {
        await imgCreateVideoRef.value.getQueryParams()
    }
    loading.value = true
    if (tabsCurrent.value === 1) {
        await editImgUploadFn()
    }
    aiGenerationVideoFn()
}


// 获取任务状态
async function getImageByTaskIdFn() {
    const res = await getImageByTaskId(taskId.value)
    if (res.data.state === 1) {
        clearInterval(timer);
        await loadingRef.value.completeLoading()
        const data = {
            id: res.data.id,
            title: queryInfo.value.title,
        }
        uni.navigateTo({
            url: `/newEditionDraw/aiVideo/detail/index?item=${JSON.stringify(data)}`,
        })
    } else if (![3, 4].includes(res.data.state)) {
        clearInterval(timer);
        const errorMessage = res.data?.remark.split('失败原因：')[1]
        Toast.fail(errorMessage);
        loading.value = false
    }
}



// 发起AI视频任务
async function aiGenerationVideoFn() {
    try {
        const data = Object.assign({}, queryParams.value, queryData.value)
        if (tabsCurrent.value === 0) {
            await textCreateVideoRef.value.setHistoryContent()
        } else {
            await imgCreateVideoRef.value.setHistoryContent()
        }
        const res = await aiGenerationVideo(data)
        taskId.value = res.data.taskId
        timer = setInterval(() => {
            getImageByTaskIdFn()
        }, 5000);
    } catch (error) {
        loading.value = false
    }
}


// 上传原图
async function editImgUploadFn() {
    return new Promise(async (resolve, reject) => {
        try {
            const res = await editImgUpload({
                type: 29,
                orgImg: queryParams.value.firstFrameUrl
            })
            queryData.value.firstFrameUrl = res.orgImgUrl
            resolve()
        } catch (error) {
            loading.value = false
            reject()
        }
    })
}

// 数据转换
function dataConversion() {
    queryInfo.value.categoryParam.forEach(item => {
        if (item.title === 'expendNum') {
            oldExpendNum.value = item.data[0].title
        }
    })
}


// 获取分类详情
async function getCategoryDetailFn() {
    const res = await getCategoryDetail(queryItem.value.id)
    queryInfo.value = res.data
    dataConversion()
}

// 加载关闭事件
function loadingClose() {
    clearInterval(timer);
}

onUnload(() => {
    clearInterval(timer);
    loading.value = false
})

onLoad((e) => {
    if (e.item) {
        queryItem.value = JSON.parse(e.item)
    }
    getCategoryDetailFn()
})
</script>

<template>
    <div class='aiVideo'>
        <NavBar>AI视频</NavBar>
        <div class="container">
            <div class="tabs">
                <div class="tab" :class="{ active: tabsCurrent === 0 }" @click="tabsCurrent = 0">文生视频</div>
                <div class="tab" :class="{ active: tabsCurrent === 1 }" @click="tabsCurrent = 1">图生视频</div>
            </div>
            <!-- 文生视频 -->
            <textCreateVideo ref="textCreateVideoRef" v-model="queryParams" v-if="tabsCurrent === 0"></textCreateVideo>
            <!-- 图生视频 -->
            <imgCreateVideo ref="imgCreateVideoRef" v-else v-model="queryParams"></imgCreateVideo>
        </div>
        <div class="footer">
            <div class="footer_placeholder"></div>
            <div class="footer_content">
                <myDrawButton :expendNum="expendNum" @click="startFn">立即生成</myDrawButton>
            </div>
        </div>
    </div>
    <van-toast id="van-toast" />
    <newLoading ref="loadingRef" v-model="loading" :duration="60000" :label="['排队中，预计等待60秒']" @close="loadingClose">
    </newLoading>
</template>

<style lang='scss' scoped>
.aiVideo {
    .container {
        padding: 0 30rpx 30rpx;

        .tabs {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 40rpx;

            .tab {
                box-sizing: border-box;
                width: 335rpx;
                height: 64rpx;
                line-height: 64rpx;
                border-radius: 32rpx;
                text-align: center;
                font-size: 30rpx;
                color: #C2C2C2;
                border: 2rpx solid transparent;

                &.active {
                    color: var(--a-main-color);
                    border: 2rpx solid var(--a-main-color);
                }
            }
        }
    }

    .footer {
        .footer_placeholder {
            height: 176rpx;
        }

        .footer_content {
            box-sizing: border-box;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 176rpx;
            background: var(--a-main-tabNav-bg-color);
            padding: 28rpx 30rpx 0;
        }
    }
}
</style>